<?php

namespace app\admin\service\auth;

use app\admin\model\Admin;
use app\admin\model\Menu;
use think\facade\Db;
use support\Log;
use app\admin\validate\AdminValidate;
use support\think\Cache;
use app\admin\service\BaseService;
class AuthService extends BaseService
{
    /**
     * 登录操作
     * @param $param
     * @return mixed
     */
    public function doLogin($param)
    {
        $data = [
            'username'  => $param['userName'],
            'password' => $param['password'],
        ];
        $validate = new AdminValidate();

        if (!$validate->check($data)) {
            return fail($validate->getError());
        }
        $admin = Admin::where('username', $data['username'])->find();
        if (empty($admin)) {
            return fail('用户不存在');
        }
        if (empty(password_verify($data['password'], $admin->password))) {
            return fail('密码错误');
        }
        if ($admin->status != 1) {
            return fail('用户已被禁用，请联系管理员');
        }
        $realIp = request()->getRealIp($safe_mode=true);
        Db::startTrans();
        try {
            $permissions = $admin->getAllPermissions($admin->id);
            $cacheKey = 'user_permission_' . $admin->id;
            Cache::set($cacheKey, $permissions, 7200);
            $data = [
                'token' => setJWT(['id' => $admin->id, 'username' => $admin->username], 1),
                'refreshToken' => setJWT(['id' => $admin->id], 7),
            ];
            $admin->last_login_at = time();
            $admin->last_login_ip = $realIp;
            $admin->updated_at = time();
            $admin->save();
            Db::commit();
            return success($data,'登录成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('登录异常：' . $e->getMessage());
            return fail('登录失败，请稍后再试');
        }
    }
}
